<template>
	<view>
		<view style="height:100vh;">
			<!-- @scrolltoupper：上滑到顶部执行事件，此处用来加载历史消息 -->
			<!-- scroll-with-animation="true" 设置滚动条位置的时候使用动画过渡，让动作更加自然 -->
			<scroll-view :scroll-into-view="scrollToView" scroll-y="true" class="messageListScrollView"
				:style="{height:scrollViewHeight}" @scrolltoupper="getHistoryChat()" scroll-with-animation="true"
				ref="chatScrollView">
				<view v-for="(message,index) in messageList" :key="message.id" :id="`message`+message.id"
					style="width: 750rpx;height: 60px;">
					<!-- <view style="height: 10px;"></view> -->
					<view v-if="message.type==0" class="messageItemLeft">
						<view style="width: 8px;"></view>
						<u--image :showLoading="true" :src="you.avatar" width="50px" height="50px"
							radius="3"></u--image>
						<view style="width: 7px;"></view>
						<view class="messageContent left">
							{{message.content}}
						</view>
					</view>
					<view v-if="message.type==1" class="messageItemRight">
						<view class="messageContent right">
							{{message.content}}
						</view>
						<view style="width: 7px;"></view>
						<u--image :showLoading="true" :src="me.avatar" width="50px" height="50px" radius="3"></u--image>
						<view style="width: 8px;"></view>
					</view>
				</view>
			</scroll-view>

			<!-- 	<scroll-view scroll-y="true" class="messageListScrollView" :scroll-top="scrollTop"
				:style="{height:scrollViewHeight}" @scrolltoupper="getHistoryChat()" scroll-with-animation="true"
				ref="chatScrollView">
				<view id="chatView">
					<view v-for="(message,index) in messageList" :key="index" :id="`message`+index"
						style="width: 750rpx;height: 60px;">
						<view style="height: 10px;"></view>
						<view v-if="message.type==0" class="messageItemLeft">
							<view style="width: 8px;"></view>
							<u--image :showLoading="true" :src="you.avatar" width="50px" height="50px"
								radius="3"></u--image>
							<view style="width: 7px;"></view>
							<view class="messageContent left">
								{{message.content}}
							</view>
						</view>
						<view v-if="message.type==1" class="messageItemRight">
							<view class="messageContent right">
								{{message.content}}
							</view>
							<view style="width: 7px;"></view>
							<u--image :showLoading="true" :src="me.avatar" width="50px" height="50px"
								radius="3"></u--image>
							<view style="width: 8px;"></view>
						</view>
					</view>
				</view>
			</scroll-view> -->

			<!-- style="top: 0vh;" -->
			<view class="messageSend">
				<view class="messageInput">
					<u--textarea v-model="messageInput" placeholder="请输入消息内容" autoHeight @focus="editHeight()">
					</u--textarea>
				</view>
				<view style="width:5px"></view>
				<view class="commmitButton" @click="send()">发 送</view>
			</view>
		</view>
	</view>
</template>

<script>
	import {
		getUserProfileVo
	} from "@/api/user";
	import {
		listChat
	} from "@/api/market/chat.js"

	let socket;
	export default {
		data() {
			return {
				webSocketUrl: "",
				socket: null,
				messageInput: '',
				// 我自己的信息
				me: {},
				// 对方信息
				you: {},

				scrollViewHeight: undefined,
				messageList: [],
				// 底部滑动到哪里
				scrollToView: '',
				page: {
					pageNum: 1,
					pageSize: 15
				},
				// maxCode: 999999,
				isFirstListChat: true,
				scrollTop: 0,
				increasingNum: 0,
			}
		},
		created() {
			this.me = uni.getStorageSync("curUser");
			// this.initWebsocket();
		},
		beforeDestroy() {
			console.log("执行销毁方法");
			this.endChat();
		},
		onLoad(e) {
			// 设置初始高度
			this.scrollViewHeight = `calc(100vh - 20px - 40px)`;
			this.you = JSON.parse(decodeURIComponent(e.you));
			uni.setNavigationBarTitle({
				title: this.you.nickname,
			})
			this.startChat();
			this.listChat();
			this.receiveMessage();
		},

		onReady() {
			// 监听键盘高度变化，以便设置输入框的高度
			uni.onKeyboardHeightChange(res => {
				let keyBoardHeight = res.height;
				console.log("keyBoardHeight:" + keyBoardHeight);
				this.scrollViewHeight = `calc(100vh - 20px - 40px - ${keyBoardHeight}px)`;

				this.scrollToView = '';
				setTimeout(() => {
					this.scrollToView = 'message' + this.messageList[this
						.messageList.length - 1].id;
				}, 150)
				// this.$nextTick(() => {
				// 	this.scrollToView = 'message' + this.messageList[this
				// 		.messageList.length - 1].id;
				// })

				// this.scrollToView = '';
				// this.$nextTick(() => {
				// 	// this.scrollToView = 'message' + this.messageList[0].id;
				// 	this.scrollToView = 'message' + this.messageList[this
				// 		.messageList.length - 1].id;
				// 	// this.scrollTop = 0;
				// 	this.increasingNum += 50;
				// 	this.toBottom();
				// })
			})
		},
		methods: {
			/**
			 * 创建websocket连接
			 */
			// initWebsocket() {
			// 	let _this = this;
			// 	this.socket = uni.connectSocket({
			// 		url: "ws://10.23.17.146:8085/websocket/" + _this.me.userName,
			// 		success(res) {
			// 			console.log('WebSocket连接成功', res);
			// 		},
			// 	})
			// 	//监听WebSocket连接打开事件
			// 	this.socket.onOpen((res) => {
			// 		console.info("监听WebSocket连接打开事件", res)
			// 	});
			// 	//接收消息
			// 	this.receiveMessage();
			// 	this.socket.onClose((close) => {
			// 		console.log('连接关闭, 正在重连')
			// 		// this.initWebsocket()
			// 	});
			// 	this.socket.onError((err) => {
			// 		console.log('连接错误, 正在重连')
			// 		// this.initWebsocket()
			// 	});
			// },
			/**
			 * 发送消息
			 */
			send() {
				if (this.messageInput != '') {
					let message = {
						from: this.me.userName,
						to: this.you.username,
						text: this.messageInput
					}
					// console.log("this.socket.send:" + this.$socket)
					// 将组装好的json发送给服务端，由服务端进行转发
					this.$socket.send({
						data: JSON.stringify(message)
					});
					let newMessage = {
						// code: this.messageList.length,
						type: 1,
						content: this.messageInput
					};
					this.messageList.push(newMessage);
					this.messageInput = '';
					// 让scroll-view自动滚动到最新的数据那里
					this.$nextTick(() => {
						this.scrollToView = 'message' + this.messageList[this
							.messageList.length - 1].id;
					});

					this.toBottom();
				}
			},
			/**
			 * 开始聊天
			 */
			startChat() {
				let message = {
					from: this.me.userName,
					to: this.you.username,
					text: "",
					status: "start"
				}
				// 告诉服务端要开始聊天了
				this.$socket.send({
					data: JSON.stringify(message)
				});
			},
			/**
			 * 结束聊天
			 */
			endChat() {
				let message = {
					from: this.me.userName,
					to: this.you.username,
					text: "",
					status: "end"
				}
				// 告诉服务端要结束聊天了
				this.$socket.send({
					data: JSON.stringify(message)
				});
			},
			/**
			 * 接收消息
			 */
			receiveMessage() {
				this.$socket.onMessage((response) => {
					// console.log("接收消息：" + response.data);
					let message = JSON.parse(response.data);

					let newMessage = {
						// code: this.messageList.length,
						type: 0,
						content: message.text
					};
					this.messageList.push(newMessage);
					// 让scroll-view自动滚动到最新的数据那里
					this.$nextTick(() => {
						this.scrollToView = 'message' + this.messageList[this
							.messageList.length - 1].id;
					});

					this.toBottom();
				})
			},
			editHeight() {
				// console.log("e:" + JSON.stringify(event.detail));
				// console.log("键盘高度：" + e.detail.height);
				// this.scrollViewHeight = `calc(100vh - 20px - 40px - ${height}px)`;

			},
			/**
			 * 查询对方和自己最近的聊天数据
			 */
			listChat() {
				return new Promise((resolve, reject) => {
					listChat(this.you.username, this.page).then(res => {
						for (var i = 0; i < res.rows.length; i++) {
							if (res.rows[i].fromWho == this.me.userName) {
								res.rows[i].type = 1;
							} else {
								res.rows[i].type = 0;
							}
							// res.rows[i].code = this.maxCode - this.messageList.length;
							// 将消息放到数组的首位
							this.messageList.unshift(res.rows[i]);
						}

						// 滑动到最底部
						if (this.isFirstListChat == true) {
							this.$nextTick(function() {
								// this.scrollToView = '';
								this.$nextTick(() => {
									this.scrollToView = 'message' + this.messageList[this
										.messageList.length - 1].id;
								});

								this.toBottom();
								this.isFirstListChat = false;
							})
						}
						resolve();
					})

				})

			},
			/**
			 * 滑到最顶端，分页加一，拉取更早的数据
			 */
			getHistoryChat() {
				console.log("下拉加载历史数据");
				this.page.pageNum++;
				this.listChat().then(() => {
					let that = this;
					this.$nextTick(() => {
						// wx.createSelectorQuery().select('#chatView').boundingClientRect(function(rect) {
						// 	console.log("现在数据高度：" + rect.height);
						// 	that.scrollTop = rect.height - that.scrollTop;
						// 	console.log("现在高度：" + that.scrollTop)
						// }).exec();
					});
				})
			},
			/**
			 * 滑动到聊天区域底部
			 */
			toBottom() {
				// this.$nextTick(() => {
				// 	console.log("滑动到底部")
				// 	this.scrollTop = this.messageList.length * 70 + this.increasingNum;
				// 	// this.scrollTop += 1000;
				// })

				// let that = this;
				// this.$nextTick(() => {
				// 	wx.createSelectorQuery().select('#chatView').boundingClientRect(function(rect) {
				// 		console.log("聊天区域高度：" + rect.height)
				// 		that.scrollTop = rect.height;
				// 	}).exec();
				// });

			}
		}
	}
</script>

<style lang="scss">
	.messageListScrollView {
		background: #F5F5F5;
		overflow: auto;

		.messageItemLeft {
			display: flex;
			align-items: flex-start;
			justify-content: flex-start;
			// height: 60px;

			.messageContent {
				max-width: calc(750rpx - 10px - 50px - 15px - 10px - 50px - 15px);
				padding: 10px;
				// margin-top: 10px;
				border-radius: 7px;
				font-family: sans-serif;
				// padding: 10px;
				// 让view只包裹文字
				width: auto;
				display: inline-block !important;
				display: inline;
			}
		}

		.messageItemRight {
			display: flex;
			align-items: flex-start;
			justify-content: flex-end;
			// height: 60px;

			.messageContent {
				max-width: calc(750rpx - 10px - 50px - 15px - 10px - 50px - 15px);
				padding: 10px;
				// margin-top: 10px;
				border-radius: 7px;
				font-family: sans-serif;
				// padding: 10px;
				// 让view只包裹文字
				width: auto;
				display: inline-block !important;
				display: inline;
			}
		}

		.right {
			background-color: #94EA68;
		}

		.left {
			background-color: #ffffff;
		}
	}

	.messageSend {
		display: flex;
		// position: relative;

		background: #ffffff;
		padding-top: 5px;
		padding-bottom: 15px;

		.messageInput {
			border: 1px #EBEDF0 solid;
			border-radius: 5px;
			width: calc(750rpx - 65px);
			margin-left: 5px;
		}

		.commmitButton {
			height: 38px;
			border-radius: 5px;
			width: 50px;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #ffffff;
			background: #3C9CFF;

		}
	}
</style>